package com.zjs.controller;

import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;
import com.zjs.common.bean.PageQuery;
import com.zjs.common.bean.ResponseResult;
import com.zjs.pojo.BcRegion;
import com.zjs.pojo.BcSubarea;
import com.zjs.service.Impl.BcDecidedZoneImpl;
import com.zjs.service.Impl.BcRegionServiceImpl;
import com.zjs.service.Impl.BcSubAreaServiceImpl;
import com.zjs.vo.BcDecidedZoneVo;
import com.zjs.vo.BcRegionVo;
import com.zjs.vo.BcSubareaVo;
import com.zjs.vo.SearchSubArea;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @类名： BcSubAreaController
 * @说明： TODO
 * @作者：SS 苏帅出品
 * @时间：2019/12/6 14:40
 * @版本：1.0
 */
@Controller
@RequestMapping(value = "bcSubarea")
public class BcSubAreaController {


    @Autowired
    BcSubAreaServiceImpl bcSubAreaService;

    @Autowired
    BcRegionServiceImpl regionService;

    @Autowired
    BcDecidedZoneImpl bcDecidedZone;

    //分页查询全部的管理分区 数据

    @RequestMapping(value = "findPage.action")
    @ResponseBody
    public Map<String,Object> findSubArea(SearchSubArea searchSub){


        Map<String, Object> allBcSubAreaVo = bcSubAreaService.findAllBcSubAreaVo(searchSub);



        //得到总数
        //PageQuery query,SearchSubArea searchSub

//        PageInfo<BcSubarea> subArea = bcSubAreaService.findSubArea(query,searchSub);
//
//        List<BcSubarea> list = subArea.getList();
//
//        List<BcSubareaVo> bcSubareaVos=new ArrayList<>();
//
//            for (BcSubarea bcSubarea:list){
//
//                BcSubareaVo subareaVo=new BcSubareaVo();
//                //复制bcSubarea 对象的全部属性 复制到BcSubareaVo对象
//                BeanUtils.copyProperties(bcSubarea,subareaVo);
//                //通过region_id得到 一个BcRegion
//                BcRegion bcRegionById = regionService.findBcRegionByIdSearchName(bcSubarea.getRegionId(),searchSub);
//
//                if (bcRegionById!=null){
//                    subareaVo.setBcRegion(bcRegionById);
//                    bcSubareaVos.add(subareaVo);
//                }
//            }



        return allBcSubAreaVo;
    }

    @RequestMapping(value = "checkId.action")
    @ResponseBody
    public Boolean findBcSubAreaById(String id){

        Boolean bcSubAreaById = bcSubAreaService.findBcSubAreaById(id);

        return bcSubAreaById;
    }

    //添加操作 或修改操作
    @RequestMapping(value = "save.action")
    @ResponseBody
    public  ResponseResult saveOruPBcSubArea(BcSubarea bcSubarea){


        int i = bcSubAreaService.saveOrUpSubArea(bcSubarea);


        if (i>0){
            return new ResponseResult(true,null);
        }

        return new ResponseResult(false,null);

    }


    //删除  /bcSubarea/delSubAreaById.action
    @RequestMapping(value = "delSubAreaById.action")
    @ResponseBody
    public ResponseResult delSubAreaById(String ids){

        int i = bcSubAreaService.delSubAreaById(ids);
        if (i>0){
            return new ResponseResult(true,null);
        }

        return new ResponseResult(false,null);
    }

    //更新 第一步
    @RequestMapping(value = "upSubAreaById.action")
    @ResponseBody
    public BcSubareaVo uPSubAreaById(String id){

      return   bcSubAreaService.findSubAreaById(id);

    }

    @RequestMapping(value = "searchSubArea.action")
    @ResponseBody
    public  ResponseResult  searchBySubArea(SearchSubArea searchSubArea, HttpServletRequest request){


        request.getSession().setAttribute("searchSub",searchSubArea);


        return new ResponseResult(true,false);
    }



    //查询出全部的城市
    @RequestMapping(value = "findProvinces.action")
    @ResponseBody
    public List<BcRegionVo> findProvinces(){


        List<BcRegionVo> regionVos=new ArrayList<>();


        String[] provinces = regionService.findProvinces();

        for (String s:provinces){

            BcRegionVo  regionVo=new BcRegionVo();

            regionVo.setId(s);

            regionVo.setName(s);

            regionVos.add(regionVo);

        }

       return regionVos;

    }

    @RequestMapping(value = "findCitys.action")
    @ResponseBody
    public List<BcRegionVo> findCitys(){

        List<BcRegionVo> regionVos=new ArrayList<>();

        String[] citys = regionService.findCitys();

        for (String s:citys){

            BcRegionVo  regionVo=new BcRegionVo();

            regionVo.setId(s);

            regionVo.setName(s);

            regionVos.add(regionVo);

        }

        return regionVos;

    }

    //导入
    @RequestMapping(value = "import.action")
    @ResponseBody
    public ResponseResult  importSubArea(MultipartFile excelFile) throws IOException {


        // 使用XSSFWorkbook 对象读取 后缀为xlsx 的Excel文件
        XSSFWorkbook workbook=new XSSFWorkbook(excelFile.getInputStream());

        //得到分区
        XSSFSheet sheetAt =workbook.getSheetAt(0);

        //得到总行数
        int lastRowNum = sheetAt.getLastRowNum();

        //用来存储读取到的每行数据
        List<BcSubarea> bcSubareas=new ArrayList<>();

        // 因为第一行 为列属性名 所以要在第二行开始 索引是0开头
        for (int i=1;i<=lastRowNum;i++){

            //得到具体的一行
            XSSFRow row = sheetAt.getRow(i);

            //得到每行的列数

            int lastCellNum = row.getLastCellNum();

            //存储读取到的一行数据
            BcSubarea bcSubarea=new BcSubarea();

            for (int j=0;j<lastCellNum;j++){


                //通过行对象 创建列对象
                XSSFCell cell = row.getCell(j);

                //设置 单元格类型为String ,因为单元格中有数字单元格，需要转为字符串
                cell.setCellType(CellType.STRING);

                switch (j){

                    case 0:
                        bcSubarea.setDecidedzoneId(cell.getStringCellValue());
                        break;
                    case 1:
                        bcSubarea.setRegionId(cell.getStringCellValue());
                        break;
                    case 2:
                        bcSubarea.setAddresskey(cell.getStringCellValue());
                        break;
                    case 3:

                        bcSubarea.setStartnum((String) cell.getStringCellValue());
                        break;
                    case 4:

                        bcSubarea.setEndnum((String)cell.getStringCellValue());
                        break;

                    case 5:

                        bcSubarea.setSingle((String)cell.getStringCellValue());
                        break;

                    case 6:
                        bcSubarea.setPosition((String)cell.getStringCellValue());
                        break;

                }

            }
            bcSubareas.add(bcSubarea);

        }


        for (BcSubarea subarea:bcSubareas){

            bcSubAreaService.saveOrUpSubArea(subarea);

        }


        //ResponseResult对象为自定义创建的 里边有两个属性 Boolean类型的 success属性  和String类型的 data属性 ,返回的是JSON格式
        return new ResponseResult(true,null);

    }

    //导出
    @RequestMapping(value = "exPort.action")
    public void exProtFile(HttpServletResponse response,HttpServletRequest request ){


        try{
            //1.查询出全部的数据


            List<BcSubarea> allSubArea = bcSubAreaService.findAllSubArea();

            // 通过固定list的长度减少资源浪费
            List<BcSubareaVo> bcSubareaVos=new ArrayList<>(allSubArea.size());


            for (BcSubarea bcSubarea:allSubArea){

                BcSubareaVo bcSubareaVo=new BcSubareaVo();

                BeanUtils.copyProperties(bcSubarea,bcSubareaVo);
                BcRegion bcRegionById=null;
                if (bcSubarea.getRegionId()!=null && !bcSubarea.getRegionId().equals("")){
                    bcRegionById= regionService.findBcRegionById(bcSubarea.getRegionId());
                }


                bcSubareaVo.setBcRegion(bcRegionById);

                bcSubareaVos.add(bcSubareaVo);

            }


            //创建workExcel工作簿

            XSSFWorkbook workbook=new XSSFWorkbook();

            //创建sheet区

            XSSFSheet exportSheet= workbook.createSheet("export");

            String[] s=new String[]{"id","decidedzoneId","regionId","addresskey","startnum","endnum","single","position","省","市","区"};



            //创建行   通过行 创建列
            XSSFRow row=null;

            XSSFCell cell=null;

            //添加 列属性   id等

            //得到需要操作的行
            row=exportSheet.createRow(0);


            for (int j=0;j<s.length;j++){

                //通过 行  创建每列
                cell = row.createCell(j);

                cell.setCellValue(s[j]);

            }



            //创建每行数据

            for (int i=0;i<bcSubareaVos.size();i++){

                //得到 需要操作的行  i+1  因为 excel表的索引是 0开始 的 而 i=0 表示第一行代表的属性列  所以需要从 第二行 开始添加
                row=exportSheet.createRow(i+1);


                //得到需要导入的 数据  一行 数据


                BcSubareaVo bcSubareaVo = bcSubareaVos.get(i);


                //操作每列

                for (int j=0;j<s.length;j++){


                    cell = row.createCell(j);

                    switch (j){

                        case 0:
                            cell.setCellValue(bcSubareaVo.getId());
                            break;
                        case 1:
                            cell.setCellValue(bcSubareaVo.getDecidedzoneId());
                            break;
                        case 2:
                            cell.setCellValue(bcSubareaVo.getRegionId());
                            break;
                        case 3:
                            cell.setCellValue(bcSubareaVo.getAddresskey());
                            break;
                        case 4:
                            cell.setCellValue(bcSubareaVo.getStartnum());
                            break;
                        case 5:
                            cell.setCellValue(bcSubareaVo.getEndnum());
                            break;
                        case 6:
                            cell.setCellValue(bcSubareaVo.getSingle());
                            break;
                        case 7:
                            cell.setCellValue(bcSubareaVo.getPosition());
                            break;
                        case 8:

                            if (bcSubareaVo.getBcRegion()!=null){
                                cell.setCellValue(bcSubareaVo.getBcRegion().getProvince());
                            }
                            break;
                        case 9:
                            if (bcSubareaVo.getBcRegion()!=null){
                                cell.setCellValue(bcSubareaVo.getBcRegion().getCity());
                            }

                            break;
                        case 10:
                            if (bcSubareaVo.getBcRegion()!=null){
                                cell.setCellValue(bcSubareaVo.getBcRegion().getDistrict());
                            }
                            break;
                    }

                }

            }




            //创建一个FileoutPutStream 输出流

            //创建一个文件夹

//            File file=new File("d://student");
//            if (!file.exists()){
//                file.mkdir();
//            }

            //创建excel的文件名
            String  fileName= URLEncoder.encode("分区管理.xlsx","UTF-8");




            response.setContentType(request.getSession().getServletContext().getMimeType(fileName));

            response.setHeader("content-disposition", "attachment;filename="+fileName);

//            FileOutputStream fileOutputStream=new FileOutputStream(new File(file,fileName));

            //将工作簿 导入电脑文件

//            ServletOutputStream outputStream = response.getOutputStream();

            workbook.write(response.getOutputStream());

//            outputStream.close();

//            //关闭 输出流
//            fileOutputStream.close();

//            return new ResponseResult(true,null);

        }catch (Exception e){
            e.getMessage();
//
//            return new ResponseResult(false,e.getMessage());

        }


    }


    //在 管理定区中显示的
    @RequestMapping(value = "findListWithoutDecidedId.action")
    @ResponseBody
    public List<BcSubarea> findListWithoutDecidedId(String id){

        List<BcSubarea> decidedIdIsNULL = bcSubAreaService.findDecidedIdIsNULL();


        if (!StringUtils.isNullOrEmpty(id)){

            List<BcSubarea> subAreaByDecidedId = bcSubAreaService.findSubAreaByDecidedId(id);

           for (BcSubarea subarea:subAreaByDecidedId){
               decidedIdIsNULL.add(subarea);
           }

        }

            return decidedIdIsNULL;
    }



}
